package awe.idea.com.web.controller;

import awe.idea.com.common.models.api.UserLoginReq;
import awe.idea.com.common.utils.R;
import awe.idea.com.common.validators.ValidatorUtils;
import awe.idea.com.service.entity.UserEntity;
import awe.idea.com.web.service.LoginService;
import awe.idea.com.web.shiro.ShiroUtils;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private Producer producer;

    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = { RequestMethod.GET,RequestMethod.POST})
    public R login(String username, String password, String captcha)throws IOException {
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!StringUtils.equalsIgnoreCase(captcha,kaptcha)){
            return R.error("验证码不正确");
        }

        UserEntity userEntity = null;
        try{
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);

            userEntity = ShiroUtils.getUserEntity();
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return R.error(e.getMessage());
        }catch (LockedAccountException e) {
            return R.error(e.getMessage());
        }catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }

        return R.ok().put("data",userEntity);
    }

    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public R logout() {
        ShiroUtils.logout();
        return R.ok();
    }

    @ResponseBody
    @RequestMapping(value ="/loginapi", method = { RequestMethod.GET,RequestMethod.POST})
    public R loginapi(String username,String password,String captcha) throws Exception{
        String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!StringUtils.equalsIgnoreCase(captcha,kaptcha)){
            return R.error("验证码不正确");
        }

        UserLoginReq userLoginReq = UserLoginReq.builder()
                .username(username)
                .password(password)
                .client("web")
                .version("1.0")
                .platform("awe")
                .captcha(captcha)
                .build();
        ValidatorUtils.validateEntity(userLoginReq);
        return loginService.loginapi(userLoginReq);
    }
}
